﻿using Microsoft.Extensions.DependencyInjection.Extensions;
using Sgr.Sms.TencentCloud;
using Sgr.Sms;
using Sgr.Utilities;
using Microsoft.Extensions.Options;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class ServiceCollectionExtensions
    {
        // 定义腾讯云支持的地域列表
        // 参考：https://cloud.tencent.com/document/api/382/52071
        private static readonly HashSet<string> ValidRegions = new(StringComparer.OrdinalIgnoreCase)
        {
            "ap-guangzhou",    // 广州
            "ap-singapore",    // 新加坡
            "ap-mumbai",       // 孟买
            "ap-tokyo",        // 东京
            "na-siliconvalley" // 硅谷
        };

        public static IServiceCollection AddTencentCloudSms(
            this IServiceCollection services,
            Action<TencentCloudSmsOptions> setupAction)
        {
            services.AddOptions<TencentCloudSmsOptions>()
                .PostConfigure(options =>
                {
                    options.CopyFrom(GetSmsTencentCloud());

                    setupAction?.Invoke(options);
                })
                .Validate(options =>
                {
                    try
                    {
                        ValidateConfig(options);
                        return true;
                    }
                    catch (OptionsValidationException)
                    {
                        throw;
                    }
                    catch (Exception ex)
                    {
                        throw new OptionsValidationException(nameof(TencentCloudSmsOptions), typeof(TencentCloudSmsOptions),
                            new[] { $"配置验证失败: {ex.Message}" });
                    }
                });

            services.TryAddEnumerable(ServiceDescriptor.Singleton<ISmsProvider, TencentCloudSmsProvider>());

            return services;
        }

        private static void ValidateConfig(TencentCloudSmsOptions options)
        {
#pragma warning disable IDE0079 // 请删除不必要的忽略
#pragma warning disable CA1861
            // 验证 SecretId
            if (string.IsNullOrWhiteSpace(options.SecretId))
                throw new OptionsValidationException(nameof(TencentCloudSmsOptions), typeof(TencentCloudSmsOptions),
                    new[] { "SecretId 不能为空" });

            // 验证 SecretKey
            if (string.IsNullOrWhiteSpace(options.SecretKey))
                throw new OptionsValidationException(nameof(TencentCloudSmsOptions), typeof(TencentCloudSmsOptions),
                    new[] { "SecretKey 不能为空" });

            // 验证 SdkAppId
            if (string.IsNullOrWhiteSpace(options.SdkAppId))
                throw new OptionsValidationException(nameof(TencentCloudSmsOptions), typeof(TencentCloudSmsOptions),
                    new[] { "SdkAppId 不能为空" });

            // 验证 SdkAppId 格式（应为数字字符串）
            if (!options.SdkAppId.All(char.IsDigit))
                throw new OptionsValidationException(nameof(TencentCloudSmsOptions), typeof(TencentCloudSmsOptions),
                    new[] { "SdkAppId 必须是数字" });

            // 验证 SignName
            if (string.IsNullOrWhiteSpace(options.SignName))
                throw new OptionsValidationException(nameof(TencentCloudSmsOptions), typeof(TencentCloudSmsOptions),
                    new[] { "SignName 不能为空" });

            // 验证 TemplateId
            if (string.IsNullOrWhiteSpace(options.TemplateId))
                throw new OptionsValidationException(nameof(TencentCloudSmsOptions), typeof(TencentCloudSmsOptions),
                    new[] { "TemplateId 不能为空" });

            // 验证 Region
            if (string.IsNullOrWhiteSpace(options.Region))
                throw new OptionsValidationException(nameof(TencentCloudSmsOptions), typeof(TencentCloudSmsOptions),
                    new[] { "Region 不能为空" });

            // 验证 Region 格式（应符合腾讯云地域命名规范，如 ap-guangzhou）
            if (!IsValidRegion(options.Region))
                throw new OptionsValidationException(nameof(TencentCloudSmsOptions), typeof(TencentCloudSmsOptions),
                    new[] { "无效的 Region 格式，应类似于 ap-guangzhou" });
#pragma warning restore CA1861
#pragma warning restore IDE0079 // 请删除不必要的忽略
        }

        private static bool IsValidRegion(string region)
        {
            return ValidRegions.Contains(region);
        }

        private static TencentCloudSmsOptions? GetSmsTencentCloud()
        {
            // 配置需要以 JSON 格式设置，因为代码中使用 JsonHelper.DeserializeObject 来解析
            //{
            //    "SecretId": "AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******",
            //    "SecretKey": "Gu5t9xGARNpq86cd98joQYCN3*******",
            //    "SdkAppId": "1400006666",
            //    "SignName": "SGR科技",
            //    "TemplateId": "1234567",
            //    "Region": "ap-guangzhou"
            //}

            //1.	Windows CMD:
            //set SGR_SMS_TENCENT_CLOUD = { "SecretId":"AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******","SecretKey":"Gu5t9xGARNpq86cd98joQYCN3*******","SdkAppId":"1400006666","SignName":"SGR科技","TemplateId":"1234567","Region":"ap-guangzhou"}

            //2.	Windows PowerShell:
            //$env: SGR_SMS_TENCENT_CLOUD = '{"SecretId":"AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******","SecretKey":"Gu5t9xGARNpq86cd98joQYCN3*******","SdkAppId":"1400006666","SignName":"SGR科技","TemplateId":"1234567","Region":"ap-guangzhou"}'

            //3.	Linux/macOS Bash:
            //export SGR_SMS_TENCENT_CLOUD = '{"SecretId":"AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******","SecretKey":"Gu5t9xGARNpq86cd98joQYCN3*******","SdkAppId":"1400006666","SignName":"SGR科技","TemplateId":"1234567","Region":"ap-guangzhou"}'

            //4.	Docker 环境变量:
            //ENV SGR_SMS_TENCENT_CLOUD = '{"SecretId":"AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******","SecretKey":"Gu5t9xGARNpq86cd98joQYCN3*******","SdkAppId":"1400006666","SignName":"SGR科技","TemplateId":"1234567","Region":"ap-guangzhou"}'

            //5.	.env 文件:
            //SGR_SMS_TENCENT_CLOUD ={ "SecretId":"AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******","SecretKey":"Gu5t9xGARNpq86cd98joQYCN3*******","SdkAppId":"1400006666","SignName":"SGR科技","TemplateId":"1234567","Region":"ap-guangzhou"}

            const string ENV_SGR_SMS_TENCENT_CLOUD = "SGR_SMS_TENCENT_CLOUD";
            string? env = EnvironmentHelper.GetEnvironmentVariable(ENV_SGR_SMS_TENCENT_CLOUD);

            try
            {
                if (!string.IsNullOrEmpty(env))
                {
                    return JsonHelper.DeserializeObject<TencentCloudSmsOptions>(env);
                }
            }
            catch { }

            return null;
        }
    }
}